package org.loofer.ext.utils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public final class XmlUtils {
    private static final String ENCODE = "utf-8";
    private static final String LOG_TAG = "XmlUtils";
    private static final String XML_TAG_ITEM_TAG = "string";

    public static Map<String, String> parse(String xmlFilePath) throws XmlPullParserException, IOException {
        return parse(new FileInputStream(xmlFilePath));
    }

    public static Map<String, String> parse(InputStream inputStream) throws XmlPullParserException, IOException {
        HashMap<String, String> map = new HashMap();
        XmlPullParser xmlParser = XmlPullParserFactory.newInstance().newPullParser();
        xmlParser.setInput(inputStream, "utf-8");
        for (int eventType = xmlParser.getEventType(); eventType != 1; eventType = xmlParser.next()) {
            switch (eventType) {
                case 2:
                    if (!xmlParser.getName().equals("string")) {
                        break;
                    }
                    String attributeValue = xmlParser.getAttributeValue(0);
                    String text = xmlParser.nextText();
                    if (attributeValue == null) {
                        break;
                    }
                    map.put(attributeValue, text);
                    break;
                default:
                    break;
            }
        }
        return map;
    }
}
